// 导入模块
const net = require("net");
const { exec } = require("child_process");
const dayjs = require("dayjs");
const config = require("./config");

// 客户端计数器
let clientCounter = 0;
const clients = new Map();

// 执行构建命令
function executeBuild(projectKey, client) {
    const project = config.PROJECTS[projectKey];
    if (!project) {
        client.write(`未知的项目: ${projectKey}\n`);
        return;
    }

    const command = `cd ${project.path} && git pull && ${project.buildCommand}`;
    exec(command, (err, stdout, stderr) => {
        if (err) {
            console.error(`构建执行出错: ${err}`);
            client.write(`构建失败: ${err.message}\n`);
            return;
        }
        if (stderr) {
            console.error(`构建警告: ${stderr}`);
            client.write(`构建警告: ${stderr}\n`);
        }
        console.log(`构建输出: ${stdout}`);
        client.write(`构建完成: ${stdout}\n`);
    });
}

// 创建TCP服务器
const server = net.createServer((client) => {
    // 检查连接数量
    if (clients.size >= config.MAX_CONNECTIONS) {
        client.end("服务器已达到最大连接数限制，请稍后重试\n");
        return;
    }

    const clientId = ++clientCounter;
    clients.set(clientId, client);
    
    console.log(`客户端 ${clientId} 已连接 - ${dayjs().format("YYYY-MM-DD HH:mm:ss")}`);
    console.log(`客户端地址: ${client.remoteAddress}, 端口: ${client.remotePort}`);

    client.write(`欢迎连接到服务器！您的客户端编号是: ${clientId}\n`);

    // 处理客户端断开连接
    client.on("end", () => {
        console.log(`客户端 ${clientId} 已断开连接`);
        clients.delete(clientId);
    });

    // 处理数据
    client.on("data", (data) => {
        try {
            const dataMessage = data.toString().trim();
            console.log(`收到客户端 ${clientId} 的消息: ${dataMessage}`);

            if (dataMessage.startsWith("/build/")) {
                const projectKey = dataMessage.replace("/build/", "");
                console.log(`开始构建项目: ${projectKey}`);
                executeBuild(projectKey, client);
            }
        } catch (err) {
            console.error(`处理客户端 ${clientId} 数据时出错: ${err}`);
            client.write(`处理消息时发生错误: ${err.message}\n`);
        }
    });

    // 处理客户端错误
    client.on("error", (err) => {
        console.error(`客户端 ${clientId} 发生错误: ${err}`);
        clients.delete(clientId);
    });
});

// 处理服务器错误
server.on("error", (err) => {
    console.error(`服务器发生错误: ${err}`);
    // 尝试优雅地关闭服务器
    server.close(() => {
        console.log("服务器已关闭，准备重启");
        // 使用非零退出码退出，触发重启
        process.exit(1);
    });
});

// 处理未捕获的异常
process.on('uncaughtException', (err) => {
    console.error('捕获到未处理的异常:', err);
    server.close(() => {
        console.log("服务器已关闭，准备重启");
        process.exit(1);
    });
});

// 处理未处理的 Promise 拒绝
process.on('unhandledRejection', (reason, promise) => {
    console.error('捕获到未处理的 Promise 拒绝:', reason);
    server.close(() => {
        console.log("服务器已关闭，准备重启");
        process.exit(1);
    });
});

// 启动服务器
server.listen(config.PORT, () => {
    console.log(`TCP服务器已启动，正在监听端口 ${config.PORT}`);
});
